package java_thinking.unit_17._17_9_10;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc:   在CountedString中添加一个char的值，它也将在构造器中初始化，然后修改hashCode和equals方法
 *          使他都包含这个char域的值
 * @author: cww
 * @DateTime: 2019-04-20 20:37
 */
class CountedString2 {
    private static List<String> created = new ArrayList<>();
    private String s;
    private char c;
    private int id;

    public CountedString2(String s, char c) {
        this.s = s;
        this.c = c;
        created.add(s);
        for (String s2 : created) {
            if (s2.equals(s)) {
                id++;
            }
        }
    }

    @Override
    public String toString() {
        return "String: " + s + " id: " + id + " char: " + c + " hashCode(): " + hashCode();
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 37 * result + s.hashCode();
        result = 37 * result + id;
        result = 37 * result + c;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof CountedString2 && s.equals(((CountedString2)obj).s) &&
                id == ((CountedString2)obj).id && c == ((CountedString2)obj).c;
    }
}
public class E26_CountedString2 {
    public static void main(String[] args) {
        Map<CountedString2,Integer> map = new HashMap<CountedString2,Integer>();
        CountedString2[] cs = new CountedString2[5];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = new CountedString2("hi",'c');
            map.put(cs[i],i);
        }
        System.out.println(map);
        for (CountedString2 csString : cs) {
            System.out.println("Looking up " + csString);
            System.out.println(map.get(csString));
        }
    }
}
